﻿using SpaceNeedle.City6473.Web.Data;
using SpaceNeedle.City6473.Web.Data.Models;
using SpaceNeedle.City6473.Web.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web.Http.Services;
using System.Configuration;
using Newtonsoft.Json;
using SpaceNeedle.City6473.WebSite.Security.Mvc;

namespace SpaceNeedle.City6473.WebSite.Controllers
{
    public class UsersController : GlobalController
    {
        //
        // GET: /Users/
        public ActionResult Index()
        {
            return View();
        }

            /// <summary>
        /// Retorna os elementos para serem colocados no DropDownList
        /// </summary>
        /// <returns>Retorna a lista da tabela informada. Caso passe o id a ser selecionado ele ficará marcado</returns>
        public List<SelectListItem> DropDownList(string role = "")
        {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "Administrador", Value = ConfigurationManager.AppSettings["adminRole"], Selected = role == ConfigurationManager.AppSettings["adminRole"] });
            list.Add(new SelectListItem { Text = "Usuário", Value = "Usuario", Selected = role == "Usuario" });

            return list;
        }

        //
        // GET: /User/Create
        //[Authorize]
        public ActionResult Create()
        {
            //if(Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            // {
            //string name = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;

            //UsersAuthentication user = new UsersAuthentication();
            // UsersAuthenticationRepository repository = new UsersAuthenticationRepository();

            var user = Auth.CurrentUser;// repository.AuthenticateAdmin(name);

            if (Auth.IsAdmin)
            {
                ViewBag.RolesList = DropDownList();
                return View();
            }
            else
            {
                Auth.SignOut();

                return RedirectToAction("Index", "Home");
            }
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                UsersAuthenticationRepository repository = new UsersAuthenticationRepository();

                UsersAuthentication user = new UsersAuthentication();
                user.Id = Guid.NewGuid();
                user.Name = collection["Name"].FormatName();
                user.Email = collection["Email"];
                user.Password = SpaceNeedle.City6473.Web.Data.Security.Encode(collection["Password"]);
                user.Roles = collection["RolesList"];
                user.IsActive = true;

                //salva
                try
                {
                    repository.Insert(user);

                    return RedirectToAction("Index", "Home");
                }
                catch { }

                return RedirectToAction("Error");

            }
            catch
            {
                ViewBag.RolesList = DropDownList();

                return View();
            }
        }
     
        /// <summary>
        /// Processa a requisição de abertura da tela de login
        /// </summary>
 
        public ActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// Executa o login do usuário
        /// </summary>
        /// <param name="user">Objeto usuário a ser logado</param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult Login(UsersAuthenticationMetaData user)
        {
            Auth.SignOut();

            //executa a pesquisa no banco
            UsersAuthenticationRepository repository = new UsersAuthenticationRepository();
            UsersAuthentication userAuthentication = new UsersAuthentication();

            userAuthentication = repository.Authenticate(user.Email, user.Password);

            if (userAuthentication != null)
            {
                Auth.CurrentUser = userAuthentication;
                
                string returnUrl = Request.QueryString["ReturnUrl"];
                if (returnUrl == null)
                    returnUrl = "~/Home/Index";

                    Response.Redirect(returnUrl);

                    return RedirectToAction("Index", "Home");

              //      #region

              //      ////para segurança, deixo uma senha falsa na sessão
              //      user.Password = "Do not you think that is too curious?";

              //      ////joga os dados necessários na sessão
              ////      Session["SessionWrapper.UserLogged"] = userAuthentication;

              //      ////retorna a página correta
              //      //// get the requested page
              //      //    string returnUrl = Request.QueryString["ReturnUrl"];
              //      if (returnUrl == null)
              //          returnUrl = "~/Home/Index";

              //      return RedirectToAction("Index", "Home");
              //      //return Redirect(returnUrl);
              //      #endregion
            }
            else
            {
                //mostra a página de informação de login incorreto
               return RedirectToAction("WrongUser", "Users");
            }
        }

         /// <summary>
        /// Carrega a página de informação de login incorreto
        /// </summary>
        public ActionResult WrongUser()
        {
            return View();
        }

        public ActionResult SignOut()
        {
            Auth.SignOut();

            return RedirectToAction("Index", "Home");
        }
	}
}